import pymysql

class stuinf:
    #打开数据库
    def __init__(self):
        self.db = pymysql.connect(host="localhost", user="root", password="", db="mydb", charset="utf8")
        self.cursor = self.db.cursor()

    def findall(self):
        #查询方法

        sql = "select * from stu2"
        try:
            print("|{0:<5}| {1:<10}| {2:<5}| {3:<10}|".format("sid", "name", "age", "classid"))
            self.cursor.execute(sql)
            alist = self.cursor.fetchall()
            for vo in alist:
                print("|{0:<5}| {1:<10}| {2:<5}| {3:<10}|".format(vo[0], vo[1], vo[2],vo[3]))

        except Exception as err:
            print("sql执行错误！原因：", err)

    def insert(self,data):
        # 添加方法

        sql = "insert into stu2(id,name,age,classid) values('%d','%s','%d','%s')" % (data)
        try:
            self.cursor.execute(sql)
            print("成功添加条数：", self.cursor.rowcount)
        except Exception as err:
            print("sql执行错误！原因：", err)

    def delete(self,id):
        # 添加方法

        sql = "delete from stu2 where id=%d"%(id)
        try:
            self.cursor.execute(sql)
            print("成功删除条数：", self.cursor.rowcount)
        except Exception as err:
            print("sql执行错误！原因：", err)

    def __del__(self):
        '''析构方法，关闭数据库'''
        self.cursor.close()
        self.db.close()

stuinf=stuinf()
#查询操作
print("查询")
stuinf.findall()
#增加操作
print("增加")
stuinf.insert((5,"wangliu",23,"python04"))
stuinf.findall()

#删除操作
print("删除")
stuinf.delete(5)
stuinf.findall()
